package com.gkt.ec.cms.activity.controller;

import com.github.pagehelper.PageInfo;
import com.gkt.ec.cms.activity.dao.OrganizationDao;
import com.gkt.ec.cms.activity.model.domain.CompanyEntity;
import com.gkt.ec.cms.activity.model.pojo.SearchCompanyVO;
import com.gkt.ec.cms.activity.service.ActivityService;
import com.gkt.ec.cms.activity.service.CompanyService;
import com.gkt.ec.cms.commons.enhance.Login;
import com.gkt.ec.cms.commons.model.domain.AdminUser;
import com.gkt.ec.commons.persistence.entity.user.Organization;
import com.gkt.library.commons.shared.utils.StringUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Huzl
 * @version 1.0.0
 */
@Controller
@RequestMapping(value = "/company")
public class CompanyController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CompanyService companyService;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private ActivityService activityService;

    @RequestMapping(value = "/list")
    public String list(Map<String, Object> model) {
        return "/company/list";
    }

    @RequestMapping(value = "/search")
    @ResponseBody
    public Object search(SearchCompanyVO searchCondition, HttpServletRequest request) {
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);
        //查询活动已绑定企业，并过滤
//        if(null != searchCondition.getActivityId()) {
//            List<CompanyEntity> companyEntityList = activityService.getCompanyByActivityId(searchCondition.getActivityId());
//            List<Long> companyIds = new ArrayList<Long>();
//            for(CompanyEntity ce : companyEntityList) {
//                companyIds.add(ce.getId());
//            }
//            searchCondition.setSelectedCompanyIds(companyIds);
//        }
        log.info("search" + searchCondition);
        PageInfo<CompanyEntity> pageInfo = companyService.queryAll(searchCondition, offset, max);
        return pageInfo;
    }

    @RequestMapping(value = "/create")
    public String create(Map<String, Object> model, @Login AdminUser user) {
        model.put("company", new CompanyEntity());
        return "/company/edit";
    }

    @RequestMapping(value = "/edit")
    public String edit(Map<String, Object> model, @RequestParam Long id, @Login AdminUser user) {
        model.put("company", companyService.get(id));
        return "/company/edit";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(CompanyEntity companyEntity, BindingResult bindingResult, @Login AdminUser user) {
        Map result = new HashMap(1);
        if (user == null)
            user = new AdminUser();
        companyEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        companyEntity.setUpdateUser(user.getId());
        if (companyEntity.getId() == null) {
            //查询新增企业名称是否有相同的数据
            List<CompanyEntity> companyList = companyService.queryCompanyByName(companyEntity.getCompanyName().replaceAll(" ", ""));
            if (CollectionUtils.isNotEmpty(companyList)) {
                result.put("resultCode", "companyNameExist");
                return result;
            }

            companyEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            companyEntity.setCreateUser(user.getId());
        }
        companyService.save(companyEntity);

        result.put("resultCode", "success");
        return result;
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam List<Long> ids) {
        companyService.deleteAll(ids);
        Map result = new HashMap(1);
        result.put("resultCode", "success");
        return result;
    }


    /**
     * 添加活动 选择企业页面
     */
    @RequestMapping(value = "/queryCompany")
    public String queryCompany(Map<String, Object> model, String isShowAddButton, Long activityId, String selectCompanyIds) {
        //活动id，修改活动时，过滤 活动已经关联的企业
        model.put("activityId", activityId);
        //已经选择的企业id列表，新增活动时， 过滤 已经选择的企业
        model.put("selectCompanyIds", selectCompanyIds);

        if (null != activityId) {
            List<CompanyEntity> companyEntityList = activityService.getCompanyByActivityId(activityId);
            List<Long> companyIds = new ArrayList<Long>();
            for (CompanyEntity ce : companyEntityList) {
                companyIds.add(ce.getId());
            }
            if (CollectionUtils.isNotEmpty(companyIds)) {
                model.put("selectCompanyIds", StringUtils.join(companyIds.toArray(), ","));
                //model.put("companyIds",companyIds.toArray());
            }
        }
        //是否展示添加,解绑企业按钮
        if (StringUtils.isNotEmpty(isShowAddButton)) {
            model.put("isShowAddButton", "1".equals(isShowAddButton) ? "1" : "0");
        }
        return "/company/queryCompany";
    }

    @RequestMapping(value = "/queryOrganization")
    @ResponseBody
    public List<Organization> queryOrganization() {
        return organizationDao.queryAll();
    }

    @RequestMapping(value = "/querySelectedCompany")
    public String querySelectedCompany(Map<String, Object> model, Long activityId) {
        model.put("activityId", activityId);
        if (null != activityId) {
            List<CompanyEntity> companyEntityList = activityService.getCompanyByActivityId(activityId);
            List<Long> companyIds = new ArrayList<Long>();
            for (CompanyEntity ce : companyEntityList) {
                companyIds.add(ce.getId());
            }
            model.put("selectedCompanyIds", companyIds);
        }
        return "/company/selectedCompany";
    }

    /**
     * 查询活动已经绑定的企业
     */
    @RequestMapping(value = "/searchSelectedCompany")
    @ResponseBody
    public Object searchSelectedCompany(SearchCompanyVO searchCondition, HttpServletRequest request) {
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);
        log.info("searchSelectedCompany" + searchCondition);
        PageInfo<CompanyEntity> pageInfo = companyService.querySelectedCompany(searchCondition, offset, max);
        return pageInfo;
    }

    @RequestMapping(value = "/querySelectCompany")
    public String querySelectCompany(Map<String, Object> model, String selectCompanyIds) {
        //已经选择的企业id列表，新增活动时， 过滤 已经选择的企业
        model.put("selectCompanyIds", selectCompanyIds);
        return "/company/selectCompany";
    }

    /**
     * 查询活动选择的企业
     */
    @RequestMapping(value = "/searchSelectCompany")
    @ResponseBody
    public Object searchSelectCompany(SearchCompanyVO searchCondition, HttpServletRequest request) {
        int offset = NumberUtils.toInt(request.getParameter("offset"), 0);
        int max = NumberUtils.toInt(request.getParameter("limit"), 15);
        log.info("searchSelectCompany" + searchCondition);
        String[] selectIds = searchCondition.getSelectCompanyIds();
        if (selectIds == null || (selectIds != null && selectIds.length == 0)) {
            return null;
        }
        PageInfo<CompanyEntity> pageInfo = companyService.querySelectCompany(searchCondition, offset, max);
        return pageInfo;
    }
}
